# Application modules
from imports import *
  
# Access a user's Profile
class Profile(object):
  def __init__(self, request):
    self.user = users.get_current_user()
    self.entity = None
    if self.user:
      self.access_url = users.create_logout_url('/')
      self.access_linktext = 'Logout'
      self.is_admin = users.is_current_user_admin()
    else:
      self.access_url = users.create_login_url(request.uri)
      self.access_linktext = 'Login'
      self.is_admin = False
      
  # Fetches profile data from the datastore
  def load(self, force = False):
    if (force or not self.entity) and self.user:
      query = db.GqlQuery("SELECT * FROM ProfileModel WHERE user = :1", self.user)
      self.entity = query.get()
      if not self.entity:
        self.entity = ProfileModel(user=self.user)
        self.entity.put()
      
      
class ProfileModel(db.Model):
  user = db.UserProperty(required=True)
  created_on = db.DateTimeProperty(auto_now_add=True)
  enabled = db.BooleanProperty(default=False)
  updated_on = db.DateTimeProperty(auto_now=True)
  locopts = db.StringProperty( \
    choices=('disabled', 'auto', 'manual'), default='disabled')
  
  
# Generalize the process > template > response workflow
class GenericPage(webapp.RequestHandler):
  # Initialize the enviroment
  def init_env(self, base_env = None):
    self.env = dict() if base_env is None else base_env[:];
    self.profile = self.env['profile'] = Profile(self.request)
    self.env['menu'] = Menu()
    
  # Send to template engine and return the request
  def send_response(self, page):
    path = os.path.join(os.path.dirname(__file__), page)
    self.response.out.write(template.render(path, self.env))

# Main Page handlers
class MainPage(GenericPage):
  def get(self):
    self.init_env()
    if self.profile: self.profile.load()
    self.send_response('index.html')
    
class ProfilePage(GenericPage):
  def get(self):
    self.init_env()
    if self.profile: self.profile.load()
    self.send_response('profile.html')
    
  def post(self):
    self.init_env()
    if self.profile: self.profile.load()
    self.profile.entity.locopts = self.request.get('locopts')
    self.profile.entity.put()
    self.env['message'] = 'Your profile has been updated!'
    self.send_response('index.html')

class FAQsPage(GenericPage):
  def get(self):
    self.init_env()
    self.send_response('faqs.html')


# Run the application
application = webapp.WSGIApplication(\
  [('/', MainPage), ('/profile', ProfilePage), ('/faqs', FAQsPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()